<template>
	<view class="chat_chat">
		
		<!-- 聊天内容 -->
		<view class="chat_content">
			<scroll-view id="scrollview" :scroll-x="false" :scroll-y="true" :style="{height: style.contentViewHeight + 'px'}" :scroll-with-animation="true" :scroll-top="scrollTop">
				<!-- 聊天内容 -->
				<view class="chat_interface_right_content"  ref="myScrollbar">
					<view class="scrollitem" v-for='(v,k) in onChat' :key="k">
						<view :class="v.send_type==0?'chat_interface_msg_item':'chat_interface_msg_item me'">
							<view class="chat_interface_msg_avatar">
								<image :src="(v.send_type==0?v.avatar:v.store_logo)||require('@/static/auth/default_avatars.png')" alt="">
							</view>
							<view :style="v.send_type==0?'float: left;':'float: right;'">
								<view class="chat_interface_msg_time"><text>{{v.send_type==0?v.nickname:v.store_name||'-'}}</text> {{v.created_at||'0000-00-00'}}</view>
								<view class="chat_interface_msg">
									<view class="chat_image" v-if="v.type=='image'" ><image :src="v.content||''" mode="aspectFit"  /></view>
									<view v-else-if="v.type=='text'">{{v.content||''}}</view>
									<view v-else>无法识别！</view>
								</view>
							</view>
						</view>
					</view>
					
		
					
				</view>
			</scroll-view>
		</view>
		
		<!-- 底部输入框 -->
		<view class="chat_bottom">
			<view class="img_btn" @click="upload()">
				<uni-icons type="image" size="24" color="#999"></uni-icons>
			</view>
			<textarea class="inputbox" v-model="sendMsg.content" placeholder="输入内容..." placeholder-style="font-size:28rpx" />
			<view class="send_btn" @click="send('text')">发送</view>
		</view>
	</view>
</template>

<script>
	import moment from "moment";  
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	export default {
		data() {
			return {
				onChat:[],
				params:{
					page:1,
					per_page:10,
				},
				// 聊天页面时时滚动样式
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0
				},
				scrollTop:-1,
				socketObj:null,
				sendMsg:{
				    type:'text', // 类型
				    content:'', // 内容
				    uid:0,
				    send_type:0,
				    store_id:0,
				},
				store_id:0,
				store_name:'',
				store_logo:'',
				isLogin:false,
				userInfo:undefined,
			};
		},
		methods:{
			onLoad(opt) {
				if(!this.$isEmpty(opt.id)){
					this.store_id = opt.id;
					this.store_name = opt.store_name;
					this.store_logo = opt.store_logo;
					uni.setNavigationBarTitle({
					　　title:opt.store_name
					})
				}else{
					// return this.$nav('',3)
				}
				this.checkLogin();
				
				const sys = uni.getSystemInfoSync();   //获取手机可使用窗口高度     api为获取系统信息同步接口
		　　　	this.style.pageHeight = sys.windowHeight;
		　　　	this.style.contentViewHeight = sys.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (100) ; //像素   因为给出的是像素高度 然后我们用的是upx  所以换算一下 
		　　　	console.log(this.style.contentViewHeight)
				this.getList();
			},
			onHide() {
				this.socketObj.close({
					complete(e) {
						console.log('关闭socket')
						console.log(e)
					}
				});
			},
			websocketInit(){
				console.log(this.isLogin)
				if(!this.isLogin){
				    return this.$toast('未登陆');
				}
			    if(typeof(WebSocket) === "undefined"){
			        // alert("您的浏览器不支持socket")
			    }else{
			        // 实例化socket
			        this.socketObj = new WebSocket(this.$api.chatUrl)
			        // 监听socket连接
			        this.socketObj.onopen = this.open;
			        // 监听socket错误信息
			        this.socketObj.onerror = this.error;
			        // 监听socket消息
			        this.socketObj.onmessage = this.getMessage;
			    }
			},
			open() {
			
			    // eslint-disable-next-line no-console
			    console.log("socket连接成功")
			
			    // 如果登录了，且用户ID存在
			    this.sendMsg.type = 'bind';
			    this.sendMsg.uid = this.userInfo.id;
			    this.sendMsg.store_id = this.store_id;
			    let infoStr = JSON.stringify(this.sendMsg);
			    if(this.userInfo.id>0){
			        this.socketObj.send(infoStr); // 发送用户ID到服务器
			        this.isBind = true; // 发送完了绑定信息
			        this.add_friend(); // 添加商家为好友
			        
			    }
			},
			error() {
			    // eslint-disable-next-line no-console
			    console.log("连接错误")
			},
			getMessage(msg) {
				if(msg == undefined){
				    return;
				}
			    let obj = JSON.parse(msg.data);
			
			    if(obj == undefined){
			        return;
			    }
			    // eslint-disable-next-line no-console
			    
			    let chatType = 1;
			    switch(obj.type){
			        case 'bind': // 绑定用户成功
			            break;
			        case 'error':
			            this.$toast('服务端消息接收失败!');
			            break;
			        case 'text': // 文字接收
			            break;
			        case 'image': // 图片接收
			            break;
			        default :  // 都不是
			            chatType = -1;
			            break;
			    }
			
			    if(chatType == -1){
			        return;
			    }
			    console.log(obj)
			    // 只要不是心跳检测，就查询一次好友列表
			    if(obj.type != '@heart@'){ 
			        
			    }
			
			    // 只要不是就处理到指定位置
			    if(obj.type != 'bind' && obj.type != 'error' && obj.type !='other'){
					
			        
					// 正在聊天则将聊天记录放入到onChat内
					if(this.store_id == obj.store_id){
						obj.store_logo = this.store_logo;
						obj.nickname = this.userInfo.nickname;
						obj.store_name = this.store_name;
						obj.avatar = this.userInfo.avatar;
						obj.created_at = moment().format('yyyy-MM-DD HH:mm:ss');
						this.onChat.push(obj) 
						this.scrollDown();
						// 如果消息存在onChat 则要清空未读记录
						// if(obj.uid != this.user_info.id){
						//     this.clearNoRead(obj.content.user_id,obj.content.to_user_id);
						// }
					}
			    }
			    
			},
			send(type) {
			    this.sendMsg.type = type;
			    this.sendMsg.store_id = this.store_id;
			    // 发送信息
				
				let obj = {...this.$api.chats}
				obj.url += '/chat_event'
				obj.method = 'post'
				let infoStr = JSON.stringify(this.sendMsg);
			    this.$http(obj,{data:infoStr}).then(res=>{
			        if(res.code == 200){
			            this.$set(this.sendMsg,'content','');
			            // console.log(this.onChat)
			            // this.scrollDown();
			        }else{
			            this.$toast(res.msg);
			        }
			    });
			    
			},
			close() {
			    // eslint-disable-next-line no-console
			    console.log("socket已经关闭")
			},
			// 把商家添加成好友
			add_friend(){
				let obj = {...this.$api.chats}
				obj.url += '/add_friend'
				obj.method = 'post'
			    this.$http(obj,{store_id:this.store_id}).then(res=>{
			        if(res.code==200){
			            // eslint-disable-next-line no-console
			            console.log(res.msg);
			        }else{
			            console.log(res.msg)
			        }
			    })
			},
			checkLogin(){
				this.$http(this.$api.checkLogin).then(res=>{
					if(res.code == 200){
						this.isLogin = true;
						this.userInfo = res.data;
						this.websocketInit()
					}else{
						this.isLogin = false;
						this.userInfo = undefined;
					}
				})
			},
			getList(){
				let obj = {...this.$api.chats}
				obj.url += '/chat_msg'
				obj.method = 'post'
				this.$http(obj,{store_id:this.store_id}).then(res=>{
					this.onChat = res.data.data.reverse()
					this.scrollDown();   //创建后调用回到底部方法
				})
			},
			upload(){
				let token = uni.getStorageSync('token');
				var _this = this;
				uni.chooseImage({
				    count: 1, //默认9
				    success: function (res) {
				        console.log(JSON.stringify(res.tempFilePaths));
						 uni.showLoading({
							title:'上传中...'
						 })
						 let obj = {..._this.$api.chats}
						 obj.url += '/image'
						 uni.uploadFile({
							 url: obj.url, //地址
							 filePath: res.tempFilePaths[0],
							 name: 'file',
							 formData: {
								 'token': token
							 },
							 success: (uploadFileRes) => {
								 let fileInfo = JSON.parse(uploadFileRes.data);
								 console.log(fileInfo.data)
								 let info = {
								     type:'image',
								     uid:_this.userInfo.id,
								     store_id:_this.store_id,
								     send_type:0,
								     content:fileInfo.data,
								 
								 };
								 // 发送信息
								 
								 let obj2 = {..._this.$api.chats}
								 obj2.url += '/chat_event'
								 obj2.method = 'post'
								 let infoStr = JSON.stringify(info);
								 _this.$http(obj2,{data:infoStr}).then(res=>{
								 
								 });
							 },
							 fail(e){
								 console.log(e)
							 },
							 complete() {
								uni.hideLoading();
							 }
						 });
				    }
				});
			},
			scrollDown() {
				let that = this;
				
				let query = uni.createSelectorQuery();
				query.selectAll('.scrollitem').boundingClientRect();
				// query.select('#scrollview').boundingClientRect();
				setTimeout(() => {
					query.exec((res) => {
						this.style.mitemHeight = 0;
						res[0].forEach((rect) => {
							this.style.mitemHeight = this.style.mitemHeight + rect.height + 40
						})   //获取所有内部子元素的高度
						console.log(this.style.mitemHeight,this.style.contentViewHeight)
						if (this.style.mitemHeight > (this.style.contentViewHeight - 100)) {   //判断子元素高度是否大于显示高度
							this.scrollTop = this.style.mitemHeight - this.style.contentViewHeight    //用子元素的高度减去显示的高度就获益获得序言滚动的高度
							console.log(this.scrollTop)
						}
		　　　　　　　})
				},50)
				
			}
		}
	}
</script>

<style lang="scss">
.chat_chat{
	.chat_bottom{
		box-shadow: 0px -3px 4px #f1f1f1;
		position: fixed;
		bottom: 0;
		height: 100rpx;
		width: 100%;
		background: #fff;
		padding: 20rpx 30rpx 0 30rpx;
		box-sizing: border-box;
		display: flex;
		.img_btn{
			flex: 0 1 120rpx;
			margin-top: 6rpx;
		}
		.inputbox{
			margin-top: 8rpx;
			flex: 0 1 100%;
			height: 46rpx;
			border-bottom: 1px solid #ddd;
			font-size: 28rpx;
		}
		.send_btn{
			color:#fff;
			background: #00aa00;
			width: 160rpx;
			height: 60rpx;
			border-radius: 6rpx;
			font-size: $uni-font-size-base;
			text-align: center;
			line-height: 60rpx;
			display: block;
			flex: 0 1 160rpx;
			margin-left: 40rpx;
		}
		&:after{
			content:'';
			display: block;
			clear: both;
		}
	}
	
	.chat_interface_right_content{
	    height:auto!important;
	    // padding-bottom: 120rpx;
	    box-sizing: border-box;
	    overflow-y: scroll;
		.chat_image{
			width: 100%;;
			image{width: 100%;height: 300rpx;}
		}
	    .chat_interface_msg_item{
	        padding: 15px 0 0 15px;
			margin-bottom: 20rpx;
			&:after{
				content:'';
				display: block;
				clear: both;
			}
	        .chat_interface_msg_avatar{
	            background-color: #efefef;
	            border-radius: 50%;
	            width: 40px;
	            height: 40px;
	            float: left;
	            margin-right: 15px;
	            image{
	                border-radius: 50%;
	                width: 100%;
	                height: 100%;
	            }
	        }
	        .chat_interface_msg_time{
	            font-size: 12px;
	            color:#666;
	            line-height: 20px;
	            text{
	                float: left;
	                font-size: 14px;
	                color:#333;
	                margin-right: 15px;
	                font-weight: bold;
	            }
	        }
	        .chat_interface_msg_time:after{
	            content:'';
	            display: block;
	            clear: both;
	        }
	        .chat_interface_msg{
	            font-size: 12px;
	            line-height: 20px;
	            padding: 5px 8px;
	            background: #efefef;
	            border-radius: 5px;
	            word-wrap:break-word;
	            // display:inline-block;
	            min-width: 140px;
	            max-width: 250px;
	            height: 100%;
				margin-top: 10rpx;
	        }
	    }
	    .me{
	        .chat_interface_msg_avatar{
	            float: right;
	        }
	        .chat_interface_msg_time{
	            float: right;
	            text{
	                float: right;
	                margin-left: 20px;
	            }
	        }
	        .chat_interface_msg{
	            background: #67C23A;
	            color:#fff;
	            float: right;
	            clear:both;
	            text-align: right;
				margin-right: 26rpx;
	        }
	    }
	    .me:after{
	        content:'';
	        display: block;
	        clear: both;
	    }
	}
}
</style>
